﻿Imports System.Data
Partial Class Content_Portafolio_Port_controls_Movimientos
    Inherits System.Web.UI.UserControl

    Dim IDataBase As New Clases.DataBase
    Dim ECConnString As String = ConfigurationManager.AppSettings("dbIP")
    Dim IControles As New Clases.controles
    Dim DIAS As String
    Dim MESS As String
    Dim YEARSS As String
    Dim valoranterior As Double

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim q1, q2 As String

            q1 = "select * from vwInst where stat_id=1"
            IControles.fill_dropDownListBaseQuery(ddl_inst, "TInstituciones", "inst_id", "inst_nombre", q1)
            'IControles.fill_dropDownListBaseQuery(ddlInstitucionB, "TInstituciones", "inst_id", "inst_nombre", q1)
            IControles.addNoneAllElement(ddl_inst)
            'IControles.addNoneAllElement(ddlInstitucionB)

            q2 = "select * from TDespachos where stat_id=1"
            IControles.fill_dropDownListBaseQuery(ddl_desp, "TDespachos", "desp_id", "desp_nombre", q2)
            IControles.fill_dropDownListBaseQuery(ddlDespachoB, "TDespachos", "desp_id", "desp_nombre", q2)
            IControles.addNoneAllElement(ddl_desp)

            IControles.addNoneAllElement(ddlC)
            IControles.addNoneAllElement(ddlCon)

            'IControles.addNoneAllElement(ddlClienteB)

            txtFechaI.Attributes.Add("onkeypress", "return false")
            txtFechaI.Attributes.Add("onPaste", "return false;")
            txtFechaF.Attributes.Add("onkeypress", "return false")
            txtFechaF.Attributes.Add("onPaste", "return false;")
            txt_Fecha.Attributes.Add("onKeyPress", "return false;")
            txt_Fecha.Attributes.Add("onPaste", "return false;")

            'textValue2.Text = Request.Form[textValue2.UniqueID]
            txt_Fecha.Text = Request.Form(txt_Fecha.UniqueID)

        End If
        RangeValidator1.MaximumValue = DateTime.Today.ToString("yyyy-MM-dd")
    End Sub

    Protected Sub btn_Registrar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_Registrar.Click
        Dim query, dmlinsert(), resultTransaction As String
        'Dim bandera As Boolean
        'bandera = ValidarFechaNac()
        'bandera = valfechas()
        'If bandera = True Then
        If ddltipo.SelectedValue = "Deposito" Then
            Dim valor, queryc As String
            Dim valoractual, montoI, nuevoval As Double
            'Dim valoractual, montoI, nuevoval As Decimal

            'valor = IDataBase.getSimpleData("Select cl_cartera from TClientes where cl_id= " & ddlC.SelectedValue, "cl_cartera")
            valor = IDataBase.getSimpleData("Select cl_cartera from TClientes where cl_id= " & ddlC.SelectedValue, "cl_cartera")
            'txtCosto.Text = Replace(datosMovimiento.Rows(0)("mov_costo"), ",", ".")
            'valoractual = Math.Round((CType(valor, Double)), 2)
            valoractual = CType(valor, Double)
            'montoI = Math.Round((CType(txt_Monto.Text, Double)), 2)
            montoI = CType(txt_Monto.Text.Replace(".", ","), Double)
            'If valoractual > montoI Then
            query = "INSERT INTO tMovimientos (movi_tipo_op, movi_fecha_op , movi_monto , cl_id , stat_id , movi_titular ) VALUES ('" & ddltipo.SelectedValue & "','" & txt_Fecha.Text & "','" & txt_Monto.Text & "','" & ddlC.SelectedValue & "',1,'" & Session("ActiveUserlogin") & "')"
            IDataBase.addStringToArray(dmlinsert, query)

            nuevoval = montoI + valoractual
            queryc = "Update TClientes set cl_cartera = " & Replace(nuevoval, ",", ".") & " where cl_id = " & ddlC.SelectedValue
            IDataBase.addStringToArray(dmlinsert, queryc)

            'query = "INSERT INTO tMovimientos (movi_tipo_op, movi_fecha_op , movi_monto , cl_id , stat_id , movi_titular ) VALUES ('" & ddltipo.SelectedValue & "','" & txt_Fecha.Text & "','" & txt_Monto.Text & "','" & ddlCon.SelectedValue & "',1,'" & Session("ActiveUserlogin") & "')"
        ElseIf ddltipo.SelectedValue = "Rendimiento" Then
            Dim valor, queryc As String
            Dim valoractual, montoI, nuevoval As Double
            'Dim valoractual, montoI, nuevoval As Decimal

            valor = IDataBase.getSimpleData("Select cl_cartera from TClientes where cl_id= " & ddlC.SelectedValue, "cl_cartera")
            'valor = Replace(IDataBase.getSimpleData("Select cl_cartera from TClientes where cl_id= " & ddlC.SelectedValue, "cl_cartera"), ",", ".")
            'valoractual = Math.Round((CType(valor, Double)), 2)
            valoractual = CType(valor, Double)
            'montoI = Math.Round((CType(txt_Monto.Text, Double)), 2)
            'montoI = CType(txt_Monto.Text, Double)
            montoI = CType(txt_Monto.Text.Replace(".", ","), Double)
            'If valoractual > montoI Then
            query = "INSERT INTO tMovimientos (movi_tipo_op, movi_fecha_op , movi_monto , cl_id , stat_id , movi_titular ) VALUES ('" & ddltipo.SelectedValue & "','" & txt_Fecha.Text & "','" & txt_Monto.Text & "','" & ddlC.SelectedValue & "',1,'" & Session("ActiveUserlogin") & "')"
            IDataBase.addStringToArray(dmlinsert, query)

            nuevoval = montoI + valoractual
            queryc = "Update TClientes set cl_cartera = " & Replace(nuevoval, ",", ".") & " where cl_id = " & ddlC.SelectedValue
            IDataBase.addStringToArray(dmlinsert, queryc)

            'query = "INSERT INTO tMovimientos (movi_tipo_op, movi_fecha_op , movi_monto , cl_id , stat_id , movi_titular ) VALUES ('" & ddltipo.SelectedValue & "','" & txt_Fecha.Text & "','" & txt_Monto.Text & "','" & ddlCon.SelectedValue & "',1,'" & Session("ActiveUserlogin") & "')"
        ElseIf ddltipo.SelectedValue = "Retiro" Then
            'valor = Replace(IDataBase.getSimpleData("Select cl_cartera from TClientes where cl_id= " & ddlC.SelectedValue, "cl_cartera"), ",", ".")
            Dim Cartera As Decimal = IDataBase.getSimpleData("Select cl_cartera from TClientes where  cl_id=" & ddlCon.SelectedValue & "", "cl_cartera")
            If txt_Monto.Text.Replace(".", ",") > Cartera Then
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('No puedes retirar más de lo que hay en cartera');", True)
                Exit Sub
            Else

                Dim valor, queryc As String
                'Dim valoractual, montoI, nuevoval As Double
                Dim valoractual, montoI, nuevoval As Decimal

                valor = IDataBase.getSimpleData("Select cl_cartera from TClientes where cl_id= " & ddlC.SelectedValue, "cl_cartera")
                'valoractual = Math.Round((CType(valor, Double)), 2)
                valoractual = CType(valor, Decimal)
                'montoI = Math.Round((CType(txt_Monto.Text, Double)), 2)
                'montoI = CType(txt_Monto.Text, Decimal)
                montoI = CType(txt_Monto.Text.Replace(".", ","), Double)
                'If valoractual > montoI Then
                query = "INSERT INTO tMovimientos (movi_tipo_op, movi_fecha_op , movi_monto , cl_id , stat_id , movi_titular ) VALUES ('" & ddltipo.SelectedValue & "','" & txt_Fecha.Text & "','" & txt_Monto.Text & "','" & ddlC.SelectedValue & "',1,'" & Session("ActiveUserlogin") & "')"
                IDataBase.addStringToArray(dmlinsert, query)

                nuevoval = valoractual - montoI
                queryc = "Update TClientes set cl_cartera = " & Replace(nuevoval, ",", ".") & " where cl_id = " & ddlC.SelectedValue
                IDataBase.addStringToArray(dmlinsert, queryc)
                'resultTransaction = IDataBase.execute_commandsArray(dmlinsert, lb_error)                    
                'Else
                'ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('No tienes suficientes fondos')", True)
                'End If

                'query = "INSERT INTO tMovimientos (movi_tipo_op, movi_fecha_op , movi_monto , cl_id , stat_id , movi_titular ) VALUES ('" & ddltipo.SelectedValue & "','" & txt_Fecha.Text & "','" & txt_Monto.Text & "','" & ddlCon.SelectedValue & "',1,'" & Session("ActiveUserlogin") & "')"
            End If
        End If
        'IDataBase.addStringToArray(dmlinsert, query)
        resultTransaction = IDataBase.execute_commandsArray(dmlinsert, lb_error)
        'Else
        'ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error la fecha ingresada no puede ser mayor ');", True)
        'Exit Sub
        'End If

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Movimiento Realizado Exitosamente');window.location.href='Movimientos.aspx'", True)
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If

    End Sub

    Protected Sub ddl_inst_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddl_inst.SelectedIndexChanged
        If ddl_inst.SelectedValue = "None" Then
            ddlC.Items.Clear()
            IControles.addNoneAllElement(ddlC)
        Else
            'Dim query As String = "SELECT distinct(NombreC) FROM vwClientes where inst_id='" & ddl_inst.SelectedValue & "' and desp_id='" & ddl_desp.SelectedValue & "' "
            If ddl_desp.SelectedValue <> "None" Then
                Dim query As String = "SELECT * FROM vwClientes where inst_id='" & ddl_inst.SelectedValue & "' and desp_id='" & ddl_desp.SelectedValue & "' "
                IControles.fill_dropDownListBaseQuery(ddlC, "vwClientes", "cl_id", "NombreC", query)
            End If
            IControles.addNoneAllElement(ddlC)
            ddlCon.Items.Clear()
            IControles.addNoneAllElement(ddlCon)
            
        End If
    End Sub

    Protected Sub ddlC_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlC.SelectedIndexChanged
        Dim query As String = "SELECT cl_id,cl_contrato FROM vwClientes where NombreC='" & ddlC.SelectedItem.ToString & "'"
        IControles.fill_dropDownListBaseQuery(ddlCon, "vwClientes", "cl_id", "cl_contrato", query)
        IControles.addNoneAllElement(ddlCon)
    End Sub

    Protected Sub ddl_desp_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddl_desp.SelectedIndexChanged
        ddl_inst.SelectedValue = "None"
        ddlC.Items.Clear()
        IControles.addNoneAllElement(ddlC)
        ddlCon.Items.Clear()
        IControles.addNoneAllElement(ddlCon)
    End Sub

    Protected Sub calculaFecha(ByVal dia As String, ByVal mes As String, ByVal years As String, ByVal febrero As String)
        Dim aux, auxi, auxil As Integer
        Dim mesN As String
        Dim diasArr(30), i As Integer
        diasArr(0) = 31
        diasArr(1) = 30
        diasArr(2) = 29
        diasArr(3) = 28
        diasArr(4) = 27
        diasArr(5) = 26
        diasArr(6) = 25
        diasArr(7) = 24
        diasArr(8) = 23
        diasArr(9) = 22
        diasArr(10) = 21
        diasArr(11) = 20
        diasArr(12) = 19
        diasArr(13) = 18
        diasArr(14) = 17
        diasArr(15) = 16
        diasArr(16) = 15
        diasArr(17) = 14
        diasArr(18) = 13
        diasArr(19) = 12
        diasArr(20) = 11
        diasArr(21) = 10
        diasArr(22) = 9
        diasArr(23) = 8
        diasArr(24) = 7
        diasArr(25) = 6
        diasArr(26) = 5
        diasArr(27) = 4
        diasArr(28) = 3
        diasArr(29) = 2
        diasArr(30) = 1

        aux = 50 - CType(dia, Integer)

        Select Case mes
            Case "1"
                If CType(dia, Integer) >= 1 And CType(dia, Integer) <= 20 Then
                    mesN = "11"
                ElseIf CType(dia, Integer) > 20 Then
                    mesN = "12"
                End If
                'mesN = "11"
            Case "2"
                If CType(dia, Integer) >= 1 And CType(dia, Integer) <= 20 Then
                    mesN = "12"
                ElseIf CType(dia, Integer) > 20 Then
                    mesN = "1"
                End If
                'mesN = "12"
            Case "3"
                If CType(dia, Integer) >= 1 And CType(dia, Integer) <= 20 Then
                    mesN = "1"
                ElseIf CType(dia, Integer) > 20 Then
                    mesN = "2"
                End If
                'mesN = "1"
            Case "4"
                If CType(dia, Integer) >= 1 And CType(dia, Integer) <= 20 Then
                    mesN = "2"
                ElseIf CType(dia, Integer) > 20 Then
                    mesN = "3"
                End If
                'mesN = "2"
            Case "5"
                If CType(dia, Integer) >= 1 And CType(dia, Integer) <= 20 Then
                    mesN = "3"
                ElseIf CType(dia, Integer) > 20 Then
                    mesN = "4"
                End If
                'mesN = "3"
            Case "6"
                If CType(dia, Integer) >= 1 And CType(dia, Integer) <= 20 Then
                    mesN = "4"
                ElseIf CType(dia, Integer) > 20 Then
                    mesN = "5"
                End If
                'mesN = "4"
            Case "7"
                If CType(dia, Integer) >= 1 And CType(dia, Integer) <= 20 Then
                    mesN = "5"
                ElseIf CType(dia, Integer) > 20 Then
                    mesN = "6"
                End If
                'mesN = "5"
            Case "8"
                If CType(dia, Integer) >= 1 And CType(dia, Integer) <= 20 Then
                    mesN = "6"
                ElseIf CType(dia, Integer) > 20 Then
                    mesN = "7"
                End If
                'mesN = "6"
            Case "9"
                If CType(dia, Integer) >= 1 And CType(dia, Integer) <= 20 Then
                    mesN = "7"
                ElseIf CType(dia, Integer) > 20 Then
                    mesN = "8"
                End If
                'mesN = "7"
            Case "10"
                If CType(dia, Integer) >= 1 And CType(dia, Integer) <= 20 Then
                    mesN = "8"
                ElseIf CType(dia, Integer) > 20 Then
                    mesN = "9"
                End If
                'mesN = "8"
            Case "11"
                If CType(dia, Integer) >= 1 And CType(dia, Integer) <= 20 Then
                    mesN = "9"
                ElseIf CType(dia, Integer) > 20 Then
                    mesN = "10"
                End If
                'mesN = "9"
            Case "12"
                If CType(dia, Integer) >= 1 And CType(dia, Integer) <= 20 Then
                    mesN = "10"
                ElseIf CType(dia, Integer) > 20 Then
                    mesN = "11"
                End If
                'mesN = "10"
        End Select

        Select Case mesN
            Case "1"
                If aux > 31 Then
                    auxi = aux - 31
                Else
                    auxi = 31 - aux
                End If
                'auxi = auxi - 1
            Case "2"
                If febrero = 28 Then
                    If aux > 28 Then
                        auxi = aux - 28
                    Else
                        auxi = 28 - aux
                    End If
                ElseIf febrero = 29 Then
                    If aux > 29 Then
                        auxi = aux - 29
                    Else
                        auxi = 29 - aux
                    End If
                End If
                'auxi = auxi - 1
            Case "3"
                If aux > 31 Then
                    auxi = aux - 31
                Else
                    auxi = 31 - aux
                End If
                'auxi = auxi - 1
            Case "4"
                If aux > 30 Then
                    auxi = aux - 30
                Else
                    auxi = 30 - aux
                End If
                'auxi = auxi - 1
            Case "5"
                If aux > 31 Then
                    auxi = aux - 31
                Else
                    auxi = 31 - aux
                End If
                'auxi = auxi - 1
            Case "6"
                If aux > 30 Then
                    auxi = aux - 30
                Else
                    auxi = 30 - aux
                End If
                'auxi = auxi - 1
            Case "7"
                If aux > 31 Then
                    auxi = aux - 31
                Else
                    auxi = 31 - aux
                End If
                'auxi = auxi - 1
            Case "8"
                If aux > 31 Then
                    auxi = aux - 31
                Else
                    auxi = 31 - aux
                End If
                'auxi = auxi - 1
            Case "9"
                If aux > 30 Then
                    auxi = aux - 30
                Else
                    auxi = 30 - aux
                End If
                'auxi = auxi - 1
            Case "10"
                If aux > 31 Then
                    auxi = aux - 31
                Else
                    auxi = 31 - aux
                End If
                'auxi = auxi - 1
            Case "11"
                If aux > 30 Then
                    auxi = aux - 30
                Else
                    auxi = 30 - aux
                End If
                'auxi = auxi - 1
            Case "12"
                If aux > 31 Then
                    auxi = aux - 31
                Else
                    auxi = 31 - aux
                End If
                'auxi = auxi - 1
        End Select

        auxi = auxi + 1
        DIAS = diasArr(auxi)
        MESS = mesN
        YEARSS = years
    End Sub

    Protected Sub btn_search_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btn_search.Click
        'Dim qryBusq As String
        'qryBusq = "Select movi_id,movi_tipo_op,Cliente,contrato,despacho,inst_nombre,movi_fecha_op,movi_monto from vwMovimientos where 1=1"

        Dim fecha As Date        
        Dim dia, mes, year, feb As String
        fecha = Now

        dia = fecha.Day
        mes = fecha.Month
        year = fecha.Year
        'MsgBox("dia: " & dia & ", mes: " & mes & ", año: " & year)
        If Date.IsLeapYear(fecha.Year) = True Then
            feb = 29
        Else
            feb = 28
        End If

        calculaFecha(dia, mes, year, feb)
        'mensaje = fecha.Day.ToString

        'MsgBox("hola: " & mensaje)
        'Dim fechaAnterior, fechaActual As Date
        'fechaAnterior = YEARSS + "-" + MESS + "-" + DIAS
        'fechaActual = year + "-" + mes + "-" + dia
        'MsgBox("fecha anterior: " & fechaAnterior)

        '-----aqui empieza la seleccion 
        Dim qryBusq As String

        qryBusq = "select * from vwMovimientos where 1 = 1 "

        If txtFechaI.Text = "" And txtFechaF.Text = "" Then
            qryBusq = qryBusq & " and movi_fecha_op between '" & YEARSS & "-" & MESS & "-" & DIAS & "' and '" & year & "-" & mes & "-" & dia & "'"
        End If

        If ddlRD.SelectedValue = 1 Then
            qryBusq = qryBusq & " and movi_tipo_op = 'Retiro' "
        ElseIf ddlRD.SelectedValue = 2 Then
            qryBusq = qryBusq & " and movi_tipo_op = 'Deposito' "
        ElseIf ddlRD.SelectedValue = 3 Then
            qryBusq = qryBusq & " and movi_tipo_op = 'Rendimiento' "
        End If

        If ddlDespachoB.SelectedValue <> "None" Then
            qryBusq = qryBusq & " and desp_id=" & ddlDespachoB.SelectedValue & ""
        End If

        'If ddlInstitucionB.SelectedValue <> "None" Then
        If busqInst.Text <> "" Then
            'qryBusq = qryBusq & " and inst_id=" & ddlInstitucionB.SelectedValue & ""
            qryBusq = qryBusq & " and inst_nombre like '%" & busqInst.Text & "%'"
        End If

        'If ddlClienteB.SelectedValue <> "None" Then
        If busqCli.Text  <> "" Then
            'qryBusq = qryBusq & " and cl_id=" & ddlClienteB.SelectedValue & ""
            qryBusq = qryBusq & " and Cliente like '%" & busqCli.Text & "%'"
        End If

        If (txtFechaI.Text <> "") And (txtFechaF.Text = "") Then
            'qryBusq = qryBusq & " and movi_fecha_op between '" & txtFechaI.Text & "' and getdate()"
            qryBusq = qryBusq & " and movi_fecha_op >= '" & txtFechaI.Text & "' and movi_fecha_op <= getdate()"
        End If

        If (txtFechaI.Text <> "") And (txtFechaF.Text <> "") Then
            'qryBusq = qryBusq & " and movi_fecha_op between '" & txtFechaI.Text & "' and '" & txtFechaF.Text & "'"
            qryBusq = qryBusq & " and movi_fecha_op >= '" & txtFechaI.Text & "' and movi_fecha_op <='" & txtFechaF.Text & "'"
        End If

        hf_repMovi.Value = qryBusq
        IControles.fillGridViewPaging(gv_Movs, qryBusq)
    End Sub

    Protected Sub gv_Movs_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gv_Movs.PageIndexChanging
        'se genera la paginación del gridview
        IControles.fillGridViewPaging(gv_Movs, hf_repMovi.Value, Convert.ToInt32(e.NewPageIndex))
    End Sub

    Protected Sub gv_Movs_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv_Movs.RowCommand
        If e.CommandName = "editarMov" Then
            'btn_Registrar.Visible = False
            'btn_update.Visible = True
            'btn_cancel.Visible = True
            clearFieldData()
            loadMoviData(e.CommandArgument)
            'ddltipo.Enabled = False
            'ddl_desp.Enabled = False
            'ddl_inst.Enabled = False
            'ddlC.Enabled = False
            'Session("modificar") = "editarMovi"

        End If

        If e.CommandName = "eliminarMov" Then
            eliminaMov(e.CommandArgument)            
        End If

    End Sub

    Protected Sub eliminaMov(ByVal id As Integer)
        Dim ope, eope, idcli, eidcli, car, ecar, mon, emon, query, dmleli(), queryc, resultTransaction As String
        Dim cartera, monto, nuevoval As Double
        mon = "Select movi_monto from vwMovimientos where movi_id = " & id
        emon = IDataBase.getSimpleData(mon, "movi_monto")
        ope = "Select movi_tipo_op from vwMovimientos where movi_id = " & id
        eope = IDataBase.getSimpleData(ope, "movi_tipo_op")
        idcli = "Select cl_id from vwMovimientos where movi_id = " & id
        eidcli = IDataBase.getSimpleData(idcli, "cl_id")
        car = "Select cl_cartera from TClientes where cl_id = " & eidcli
        ecar = IDataBase.getSimpleData(car, "cl_cartera")

        cartera = CType(ecar, Double)
        monto = CType(emon, Double)
        If eope = "Deposito" Then

            query = "Delete from tMovimientos where movi_id = " & id
            IDataBase.addStringToArray(dmleli, query)

            nuevoval = cartera - monto
            queryc = "Update TClientes set cl_cartera = " & Replace(nuevoval, ",", ".") & " where cl_id = " & eidcli
            IDataBase.addStringToArray(dmleli, queryc)
        ElseIf eope = "Retiro" Then
            query = "Delete from tMovimientos where movi_id = " & id
            IDataBase.addStringToArray(dmleli, query)

            nuevoval = cartera + monto
            queryc = "Update TClientes set cl_cartera = " & Replace(nuevoval, ",", ".") & " where cl_id = " & eidcli
            IDataBase.addStringToArray(dmleli, queryc)
        ElseIf eope = "Rendimiento" Then
            query = "Delete from tMovimientos where movi_id = " & id
            IDataBase.addStringToArray(dmleli, query)

            nuevoval = cartera - monto
            queryc = "Update TClientes set cl_cartera = " & Replace(nuevoval, ",", ".") & " where cl_id = " & eidcli
            IDataBase.addStringToArray(dmleli, queryc)
        End If

        resultTransaction = IDataBase.execute_commandsArray(dmleli, lb_error)

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Movimiento Eliminado Exitosamente');window.location.href='Movimientos.aspx'", True)
        Else

            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If
    End Sub

    Protected Sub clearFieldData()
        btn_Registrar.Visible = True
        btn_update.Visible = False
        ddl_desp.SelectedValue = "None"
        ddl_inst.SelectedValue = "None"
        ddlC.SelectedIndex = -1
        ddlCon.SelectedIndex = -1
        txt_Fecha.Text = ""
        txtCartera.Text = ""
        txt_Monto.Text = ""
        ddltipo.Enabled = True
        ddl_desp.Enabled = True
        ddl_inst.Enabled = True
        ddlC.Enabled = True
        txt_Fecha.Enabled = True
        img_cal1.Visible = True

    End Sub

    Protected Sub loadMoviData(ByVal movi_id As String)
        Dim datosMovi As New DataTable
        Dim dmlGetMoviData As String


        ddlC.Items.Clear()
        ddlCon.Items.Clear()

        ddltipo.Enabled = False
        ddl_desp.Enabled = False
        ddl_inst.Enabled = False
        ddlC.Enabled = False
        ddlCon.Enabled = False
        'txt_Fecha.Enabled = False
        'img_cal1.Visible = False


        btn_Registrar.Visible = False
        btn_update.Visible = True
        btn_cancel.Visible = True

        dmlGetMoviData = "select Distinct Top 1 * from vwMovimientos where movi_id = '" & movi_id & "' "
        IDataBase.createDataTable(datosMovi, dmlGetMoviData)
        If datosMovi IsNot Nothing Then
            ddltipo.SelectedValue = datosMovi.Rows(0)("movi_tipo_op")
            ddl_desp.SelectedValue = datosMovi.Rows(0)("desp_id")
            ddl_inst.SelectedValue = datosMovi.Rows(0)("inst_id")


            Dim query As String = "SELECT distinct(NombreC) FROM vwClientes where inst_id='" & ddl_inst.SelectedValue & "' and desp_id='" & ddl_desp.SelectedValue & "' "
            IControles.fill_dropDownListBaseQuery(ddlC, "vwClientes", "NombreC", "NombreC", query)
            ddlC.SelectedValue = datosMovi.Rows(0)("Cliente")
            IControles.addNoneAllElement(ddlC)


            Dim query2, query3, equery3, q4, eq4 As String
            query2 = "Select * from vwClientes where desp_id='" & ddl_desp.SelectedValue & "' and inst_id='" & ddl_inst.SelectedValue & "' and NombreC='" & ddlC.SelectedItem.ToString & "' "

            IControles.fill_dropDownListBaseQuery(ddlCon, "vwClientes", "cl_id", "cl_contrato", query2)
            ddlCon.SelectedValue = datosMovi.Rows(0)("cl_id")
            IControles.addNoneAllElement(ddlCon)

            query3 = "Select cl_id from vwClientes where desp_id='" & ddl_desp.SelectedValue & "' and inst_id='" & ddl_inst.SelectedValue & "' and NombreC='" & ddlC.SelectedItem.ToString & "' "
            equery3 = IDataBase.getSimpleData(query3, "cl_id")
            q4 = "Select cl_cartera from TClientes where cl_id = " & equery3
            eq4 = IDataBase.getSimpleData(q4, "cl_cartera")
            txtCartera.Text = eq4

            txt_Monto.Text = Replace(datosMovi.Rows(0)("movi_monto"), ",", ".")
            'hf_monto.value = datosMovi.Rows(0)("movi_monto")
            txt_Fecha.Text = CType(datosMovi.Rows(0)("movi_fecha_op"), Date).ToString("yyyy-MM-dd")



        End If

        'hf_id.Value = movi_id
        Session("movimiento_id") = movi_id

    End Sub

    Protected Sub btn_cancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_cancel.Click
        clearFieldData()
    End Sub

    Protected Sub btn_update_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_update.Click
        Dim query, dmlupdate(), resultTransaction As String

        If ddltipo.SelectedValue = "Deposito" Then

            Dim ayu, ayuda, valanteriorcartera, carant, queryc As String
            Dim montoI, nuevoval As Double
            ayu = "Select movi_monto from vwMovimientos where movi_id = " & Session("movimiento_id")
            ayuda = IDataBase.getSimpleData(ayu, "movi_monto")
            valoranterior = CType(ayuda, Double)
            valanteriorcartera = IDataBase.getSimpleData("Select cl_cartera from vwClientes where cl_id = " & ddlCon.SelectedValue, "cl_cartera")
            'valanteriorcartera = IDataBase.getSimpleData("Select cl_cartera from TClientes where cl_contrato = " & hf_clid.Value, "cl_cartera")
            carant = CType(valanteriorcartera, Double) - valoranterior
            'If carant > CType(txt_Monto.Text, Double) Then
            query = "Update TMovimientos set movi_tipo_op='" & ddltipo.SelectedValue & "',movi_fecha_op='" & txt_Fecha.Text & "',movi_monto='" & txt_Monto.Text & "',cl_id='" & ddlCon.SelectedValue & _
                    "',movi_titular='" & Session("ActiveUserlogin") & "' where movi_id=" & Session("movimiento_id")
            IDataBase.addStringToArray(dmlupdate, query)
            montoI = CType(txt_Monto.Text.Replace(".", ","), Double)
            nuevoval = carant + montoI
            queryc = "Update TClientes set cl_cartera = " & Replace(nuevoval, ",", ".") & " where cl_id = " & ddlCon.SelectedValue
            IDataBase.addStringToArray(dmlupdate, queryc)

            'IDataBase.addStringToArray(dmlupdate, " exec spRevierteMovimientos " & hf_id.Value & ", 1")
            'query = "Update TMovimientos set  cl_id= " & ddlCon.SelectedValue & ", movi_monto=" & txt_Monto.Text & " where movi_id=" & hf_id.Value & ""
        ElseIf ddltipo.SelectedValue = "Rendimiento" Then

            Dim ayu, ayuda, valanteriorcartera, carant, queryc As String
            Dim montoI, nuevoval As Double
            ayu = "Select movi_monto from vwMovimientos where movi_id = " & Session("movimiento_id")
            ayuda = IDataBase.getSimpleData(ayu, "movi_monto")
            valoranterior = CType(ayuda, Double)
            valanteriorcartera = IDataBase.getSimpleData("Select cl_cartera from vwClientes where cl_id = " & ddlCon.SelectedValue, "cl_cartera")
            'valanteriorcartera = IDataBase.getSimpleData("Select cl_cartera from TClientes where cl_contrato = " & hf_clid.Value, "cl_cartera")
            carant = CType(valanteriorcartera, Double) - valoranterior
            'If carant > CType(txt_Monto.Text, Double) Then
            query = "Update TMovimientos set movi_tipo_op='" & ddltipo.SelectedValue & "',movi_fecha_op='" & txt_Fecha.Text & "',movi_monto='" & txt_Monto.Text & "',cl_id='" & ddlCon.SelectedValue & _
                    "',movi_titular='" & Session("ActiveUserlogin") & "' where movi_id=" & Session("movimiento_id")
            IDataBase.addStringToArray(dmlupdate, query)
            montoI = CType(txt_Monto.Text.Replace(".", ","), Double)
            nuevoval = carant + montoI
            queryc = "Update TClientes set cl_cartera = " & Replace(nuevoval, ",", ".") & " where cl_id = " & ddlCon.SelectedValue
            IDataBase.addStringToArray(dmlupdate, queryc)

            'IDataBase.addStringToArray(dmlupdate, " exec spRevierteMovimientos " & hf_id.Value & ", 1")
            'query = "Update TMovimientos set  cl_id= " & ddlCon.SelectedValue & ", movi_monto=" & txt_Monto.Text & " where movi_id=" & hf_id.Value & ""
        ElseIf ddltipo.SelectedValue = "Retiro" Then
            'Dim Cartera As Decimal = IDataBase.getSimpleData("Select cl_cartera from TClientes where  cl_id=" & ddlCon.SelectedValue & "", "cl_cartera")
            Dim Cartera As Decimal = IDataBase.getSimpleData("Select cl_cartera from TClientes where  cl_id=" & ddlCon.SelectedValue & "", "cl_cartera")
            'Cartera = Cartera + hf_monto.Value
            If txt_Monto.Text.Replace(".", ",") > Cartera Then
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('No puedes retirar más de lo que hay en cartera');", True)
                Exit Sub
            Else
                Dim ayu, ayuda, valanteriorcartera, carant, queryc As String
                Dim montoI, nuevoval As Double
                ayu = "Select movi_monto from vwMovimientos where movi_id = " & Session("movimiento_id")
                ayuda = IDataBase.getSimpleData(ayu, "movi_monto")
                valoranterior = CType(ayuda, Double)
                valanteriorcartera = IDataBase.getSimpleData("Select cl_cartera from vwClientes where cl_id = " & ddlCon.SelectedValue, "cl_cartera")
                'valanteriorcartera = IDataBase.getSimpleData("Select cl_cartera from TClientes where cl_contrato = " & hf_clid.Value, "cl_cartera")
                carant = CType(valanteriorcartera, Double) + valoranterior
                'If carant > CType(txt_Monto.Text, Double) Then
                query = "Update TMovimientos set movi_tipo_op='" & ddltipo.SelectedValue & "',movi_fecha_op='" & txt_Fecha.Text & "',movi_monto='" & txt_Monto.Text & "',cl_id='" & ddlCon.SelectedValue & _
                        "',movi_titular='" & Session("ActiveUserlogin") & "' where movi_id=" & Session("movimiento_id")
                IDataBase.addStringToArray(dmlupdate, query)
                montoI = CType(txt_Monto.Text.Replace(".", ","), Double)
                nuevoval = carant - montoI
                queryc = "Update TClientes set cl_cartera = " & Replace(nuevoval, ",", ".") & " where cl_id = " & ddlCon.SelectedValue
                IDataBase.addStringToArray(dmlupdate, queryc)
                'End If

                'IDataBase.addStringToArray(dmlupdate, " exec spRevierteMovimientos " & hf_id.Value & ", 2")
                'query = "Update TMovimientos set  cl_id= " & ddlCon.SelectedValue & ", movi_monto=" & txt_Monto.Text & " where movi_id=" & hf_id.Value & ""
            End If
        End If

        'IDataBase.addStringToArray(dmlupdate, query)

        resultTransaction = IDataBase.execute_commandsArray(dmlupdate, lb_error)
        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Movimiento Modificado Exitosamente');window.location.href='Movimientos.aspx'", True)
        Else

            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If


    End Sub

    Protected Sub ddlCon_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCon.SelectedIndexChanged
        Dim query As String = "SELECT cl_cartera FROM vwClientes where NombreC='" & ddlC.SelectedItem.ToString & "'"
        txtCartera.Text = IDataBase.getSimpleData(query, "cl_cartera")
        'txtCartera.Text = Replace(IDataBase.getSimpleData(query, "cl_cartera"), ",", ".")
        'txtCosto.Text = Replace(datosMovimiento.Rows(0)("mov_costo"), ",", ".")
    End Sub

   Private Sub ValFechas()
        RangeValidator1.MinimumValue = "01/01/1900"
        RangeValidator1.MaximumValue = DateTime.Today.ToString("yyyy-MM-dd")
        RangeValidator1.ErrorMessage = "La fecha del operación no puede ser mayor al día de Hoy"
    End Sub

    'Public Function ValidarFechaNac() As Boolean
    '    Dim fechaProblema, fp2 As DateTime

    '    'fp2 = CType(txt_Fecha.Text, Date)
    '    If Not DateTime.TryParse(txt_Fecha.Text, fechaProblema) Then
    '        'MsgBox("La fecha ingresada no es válida", MsgBoxStyle.Exclamation, "Error")
    '        ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('La fecha ingresada no es válida ');", True)
    '        txt_Fecha.Text = ""
    '        Return False
    '    End If

    '    Dim fechaMaxima As New DateTime(2050, 1, 1)
    '    Dim fechaMinima As New DateTime(1950, 1, 1)

    '    If (fechaProblema < fechaMinima) Or (fechaProblema > fechaMaxima) Then

    '        'MsgBox("La fecha ingresada no es válida", MsgBoxStyle.Exclamation, "Error")
    '        ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('La fecha ingresada no es válida ');", True)
    '        txt_Fecha.Text = ""
    '        Return False
    '        'Return True
    '    ElseIf fechaProblema > Now Then
    '        Return False
    '    Else
    '        'Return False
    '        Return True
    '    End If

    '    Return True
    'End Function

End Class
